package com.nulldev.util.web.HttpClient.providers.websockets;

import com.nulldev.util.web.HttpClient.providers.websockets.HttpWebSocket.WebSocketMessageType;

public interface WebSocketListener {

	public static class Message {
		public final WebSocketMessageType type;
		private final Object obj;

		public Message(final String message, final WebSocketMessageType type) {
			this.type = type;
			this.obj = message;
		}

		public Message(final byte[] message, final WebSocketMessageType type) {
			this.type = type;
			this.obj = message;
		}

		public Object getObject() {
			return this.obj;
		}

		public String asString() {
			if (this.obj instanceof String)
				return ((String) this.obj);
			if (this.obj instanceof byte[])
				return new String((byte[]) this.obj);
			throw new UnsupportedOperationException("Unknown object: " + this.obj);
		}

		public byte[] asBytes() {
			if (this.obj instanceof String)
				return ((String) this.obj).getBytes();
			if (this.obj instanceof byte[])
				return ((byte[]) this.obj);
			throw new UnsupportedOperationException("Unknown object: " + this.obj);
		}

		public WebSocketMessageType getType() {
			return this.type;
		}

		@Override
		public String toString() {
			switch (this.type) {
				case BINARY:
					return "Message[type=" + this.type + ",contents=" + new String((byte[]) this.obj) + "]";
				case TEXT:
					return "Message[type=" + this.type + ",contents=" + ((String) this.obj) + "]";
				default:
					return super.toString();
			}
		}
	}

	public void onMessage(final Message message);

	public void onConnect();

	public void onError(final Throwable t);

	public void onClosed();
}
